package message;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

import event.Direction;
import event.Tank;
import user.source.TankClient;

/**
 * 
 * @author
 *
 */
public class TankMoveMsg implements Msg {
	int msgType = Msg.TANK_MOVE_MSG;
	int x, y;
	int id;
	Direction barrel;
	Direction dir;
	TankClient tc;

	public TankMoveMsg(int id, int x, int y, Direction dir, Direction barrel) {

		this.id = id;
		this.x = x;
		this.y = y;
		this.dir = dir;
		this.barrel = barrel;
	}

	public TankMoveMsg(TankClient tc) {
		this.tc = tc;
	}

	@Override
	public void send(DatagramSocket ds, String ip, int udpPort) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(baos);
		try {
			// 将信息类型发送出去
			dos.writeInt(msgType);
			dos.writeInt(id);
			dos.writeInt(x);
			dos.writeInt(y);
			dos.writeInt(dir.ordinal());
			dos.writeInt(barrel.ordinal());
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] buffer = baos.toByteArray();

		try {
			DatagramPacket dp = new DatagramPacket(buffer, buffer.length, new InetSocketAddress(ip, udpPort));
			ds.send(dp);
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void parse(DataInputStream dis) {
		try {
			int id = dis.readInt();
			// 如果坦克的id号和自己的一样，那么这个包没有用处，直接跳过
			if (tc.myTank.id == id) {
				return;
			}
			int x = dis.readInt();
			int y = dis.readInt();
			Direction dir = Direction.values()[dis.readInt()];
			Direction barrel = Direction.values()[dis.readInt()];

			@SuppressWarnings("unused")
			boolean exist = false;
			for (int i = 0; i < tc.tanks.size(); i++) {
				Tank tank = tc.tanks.get(i);
				if (tank.id == id) {
					tank.x = x;
					tank.y = y;
					tank.dir = dir;
					tank.barrel = barrel;
					exist = true;
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
